package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.common.result.Result;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author lsyandwh
 * @since 2022-12-02
 */
@RestController
@RequestMapping("/admin/core/dict")
//@CrossOrigin
@Api(tags = "数字字典管理")
public class AdminDictController {

    @Autowired
    private DictService dictService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String CACHE_KEY = "admin.core.dict.";

    @ApiOperation("添加数据")
    @PostMapping("/save")
    public Result save(@RequestBody Dict dict){
        //将缓存中所有关于字典的数据进行删除
        Set keys = redisTemplate.keys(CACHE_KEY + "*");
        redisTemplate.delete(keys);

        dictService.save(dict);
        return Result.ok();
    }

    @ApiOperation("根据id进行修改")
    @PutMapping("/edit")
    public Result edit(@RequestBody Dict dict){

        //将缓存中所有关于字典的数据进行删除
        Set keys = redisTemplate.keys(CACHE_KEY + "*");
        redisTemplate.delete(keys);

        dictService.updateById(dict);
        return Result.ok();
    }

    @ApiOperation("根据id进行查询")
    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable Long id){
        Dict dict = dictService.getById(id);
        return Result.ok().data("dict",dict);
    }

    @ApiOperation("根据id进行删除")
    @DeleteMapping("/removeById/{id}")
    public Result removeById(@PathVariable Long id){

        //将缓存中所有关于字典的数据进行删除
        Set keys = redisTemplate.keys(CACHE_KEY + "*");
        redisTemplate.delete(keys);

        boolean b = dictService.removeById(id);
        return Result.ok().data("b",b);
    }

    @ApiOperation("根据parentId查询子节点")
    @GetMapping("/getByParentId/{parentId}")
    public Result getByParentId(@PathVariable("parentId") Long parentId){

        List<Dict> dictList = dictService.getByParentId(parentId);

        return Result.ok().data("list",dictList);
    }

    @ApiOperation("批量添加数据字典")
    @PostMapping("/import")
    public Result importDict(@RequestParam MultipartFile file) throws IOException {

        //将缓存中所有关于字典的数据进行删除
        Set keys = redisTemplate.keys(CACHE_KEY + "*");
        redisTemplate.delete(keys);

        InputStream inputStream = file.getInputStream();
        dictService.insertBatch(inputStream);

        return Result.ok();
    }

    @ApiOperation("导出数据字典")
    @GetMapping("/export")
    public void exportDict(HttpServletResponse response){
        //获取输出流
        ServletOutputStream outputStream = null;

        List<ExcelDictDTO> list = dictService.exportDict();
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //写出数据
        EasyExcel.write(outputStream,ExcelDictDTO.class).sheet("数据字典").doWrite(list);
    }

}

